/**
 * @desc 上传组件
 * @props { bool } disabled 是否显示上传控件
 * @props { number | string } 上传数量
 */
import React from "react";
import PropTypes from "prop-types";
import { Upload, Modal } from "antd";
import { PlusOutlined } from "@ant-design/icons";
import { withRouter } from "react-router-dom";
import { getBase } from "@/utils/getBase";
import lrz from "lrz";
class FormUpload extends React.Component {
  state = {
    previewVisible: false,
    previewImage: "",
    previewTitle: "",
    fileList: []
  };

  handleCancel = () => this.setState({ previewVisible: false });

  handlePreview = async file => {
    if (!file.url && !file.preview) {
      file.preview = await getBase(file.originFileObj);
    }

    this.setState({
      previewImage: file.url || file.preview,
      previewVisible: true,
      previewTitle:
        file.name || file.url.substring(file.url.lastIndexOf("/") + 1)
    });
  };
  async handleBeforeUpload(fileSource) {
    const getImgFile = await this.reChangeImage(fileSource);
    return false;
  }
  async reChangeImage(fileSource) {
    return new Promise((resolve, reject) => {
      lrz(fileSource, { width: this.state.width }).then(res => {
        if (res instanceof Object) {
          //将压缩后的base64字符串转换为文件对象
          let file = new File([res.file], fileSource.name);
          Object.assign(file, { uid: file.lastModified });
          return resolve(file);
        } else {
          return reject(true);
        }
      });
    });
  }
  handleChange = ({ fileList }) => {
    this.props.getFiles(fileList);
    this.setState({ fileList });
  };

  render() {
    const { previewVisible, previewImage, fileList, previewTitle } = this.state;
    const { len, disabled } = this.props;
    const uploadButton = (
      <div>
        <PlusOutlined />
        <div style={{ marginTop: 8 }}>Upload</div>
      </div>
    );
    return (
      <>
        <Upload
          action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
          listType="picture-card"
          // beforeUpload = { this.handleBeforeUpload }
          fileList={fileList}
          multiple
          onPreview={this.handlePreview}
          onChange={this.handleChange}
        >
          {fileList.length >= len || disabled ? null : uploadButton}
        </Upload>
        <Modal
          visible={previewVisible}
          title={previewTitle}
          footer={null}
          onCancel={this.handleCancel}
        >
          <img alt="example" style={{ width: "100%" }} src={previewImage} />
        </Modal>
      </>
    );
  }
}
FormUpload.propTypes = {
  disabled: PropTypes.bool, //上传按钮是否显示
  len: PropTypes.number, //最大上传数量
  getFiles: PropTypes.func.isRequired
};
FormUpload.defaultProps = {
  disabled: false,
  len: 5
};
export default withRouter(FormUpload);
